package org.example.fileservice.controller;

import org.example.fileservice.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.example.fileservice.pojo.FileInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            FileInfo fileInfo = fileService.uploadFile(file);
            result.put("success", true);
            result.put("data", fileInfo);
            result.put("message", "文件上传成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文件上传失败: " + e.getMessage());
        }
        return result;
    }

    @GetMapping("/list")
    public Map<String, Object> getFileList() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<FileInfo> files = fileService.list();
            result.put("success", true);
            result.put("data", files);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取文件列表失败: " + e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}")
    public Map<String, Object> getFileById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            FileInfo fileInfo = fileService.getById(id);
            result.put("success", true);
            result.put("data", fileInfo);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取文件信息失败: " + e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}/content")
    public String getFileContent(@PathVariable Long id) {
        try {
            FileInfo fileInfo = fileService.getById(id);
            if (fileInfo != null && fileInfo.getFileContent() != null) {
                return fileInfo.getFileContent();
            }
            return "文件内容不存在或未解析完成";
        } catch (Exception e) {
            return "获取文件内容失败: " + e.getMessage();
        }
    }
    @DeleteMapping("/clear")
    public Map<String, Object> clearAllFiles() {
        Map<String, Object> result = new HashMap<>();
        try {
            fileService.clearAllFiles();
            result.put("success", true);
            result.put("message", "所有文件已清空");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "清空文件失败: " + e.getMessage());
        }
        return result;
    }
}